package com.rbmh.network.service.impl;

import cn.hutool.db.DaoTemplate;
import com.rbmh.network.bean.entity.DbInfo;
import com.rbmh.network.bean.entity.PageResult;
import com.rbmh.network.dao.Mapper.DbInfoMapper;
import com.rbmh.network.service.DbConnectService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class DbConnectServiceImpl implements DbConnectService {

    private static final Logger logger = LoggerFactory.getLogger(DbConnectServiceImpl.class);
    @Autowired
    private DbInfoMapper  dbInfoMapper;

    /**
     * 测试连接高斯数据库
     * @param dbInfo 服务器信息实体
     * @return true表示连接成功，false表示连接失败
     */
    public boolean testGaussDBConnection(DbInfo dbInfo) {
        String ip = dbInfo.getIpAddress();
        int port = dbInfo.getPort();
        String dbName = dbInfo.getDbName();
        String username = dbInfo.getUsername();
        String password = dbInfo.getPassword();
        // 1. 参数校验
        if (ip == null || ip.isEmpty() || port <= 0 || dbName == null || dbName.isEmpty()) {
            logger.error("参数校验失败: ip={}, port={}, dbName={}", ip, port, dbName);
            return false;
        }

        // 2. 配置连接池
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(String.format("jdbc:postgresql://%s:%d/%s", ip, port, dbName));
//        config.setDriverClassName("com.huaweicloud.dws.jdbc.DWSDriver");
//        config.setJdbcUrl("jdbc:dws://cluster-address:port/database");
        config.setUsername(username);
        config.setPassword(password);

        // 连接池优化配置
        config.setMaximumPoolSize(1); // 测试连接只需1个连接
        config.setConnectionTimeout(3000); // 3秒连接超时
        config.setIdleTimeout(60000); // 60秒空闲超时
        config.setMaxLifetime(180000); // 3分钟最大生命周期

        // 高斯数据库特定参数
        config.addDataSourceProperty("prepareThreshold", "0");
        config.addDataSourceProperty("batchMode", "off");
        config.addDataSourceProperty("socketTimeout", "3000");

        // 3. 测试连接
        try (HikariDataSource ds = new HikariDataSource(config);
             Connection conn = ds.getConnection()) {

            // 执行简单测试查询验证连接有效性
            try (var stmt = conn.createStatement();
                 var rs = stmt.executeQuery("SELECT 1")) {
                if (rs.next()) {
                    logger.info("✅ 成功连接到高斯数据库 {}:{}", ip, port);
                    dbInfo.setCreateTime(new Date());
                    dbInfo.setUpdateTime(new Date());
                    dbInfoMapper.insert(dbInfo);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("连接高斯数据库失败: {}:{}, 错误: {}", ip, port, e.getMessage());
            logger.debug("连接失败详情:", e);
        }

        return false;
    }


    @Override
    public boolean dbConnect(DbInfo dbInfo) {
        // 调用测试连接方法
        boolean isConnected = testGaussDBConnection(dbInfo);

        if (isConnected) {
            logger.info("数据库连接测试成功");
            return  true;
        } else {
            logger.error("数据库连接测试失败");
            return  false;
        }
    }


    @Override
    public List<DbInfo> selectByPage(String province, String city, String district,
                                     String detailAddress, String ipAddress,
                                     String orderBy, String orderDir,
                                     int offset, int pageSize) {
        return dbInfoMapper.selectByPage(province, city, district, detailAddress, ipAddress,
                orderBy, orderDir, offset, pageSize);
    }

    @Override
    public int countByConditions(String province, String city, String district,
                                 String detailAddress, String ipAddress) {
        return dbInfoMapper.countByConditions(province, city, district, detailAddress, ipAddress);
    }


    @Override
    public int deleteById(Long id) {
        return dbInfoMapper.deleteById(id);
    }
}
